#!/usr/bin/python3
#coding=utf-8


import os
import sys
import time
import datetime
import smtplib
from log import CLog
from mysqlDB import CMySqlDB

#使用前需要/home/user0/rem_one源目录和5个标准数据库，执行需要python3环境
#安装源 0 从服务器默认模板安装  1:从文件恢复,需要将数据库备份文件放在当前文件夹下
installOrigaType=0

#安装实例序号头       20:20000 21:21000 22:22000 ......  30:30000
#支持格式"20" "21,22,23" "20-40"

installInstanceUser="20-22"

#安装前检测实例是否存在，若存在 0:停止安装 1:覆盖实例
ifInstanceUserExit=1

#服务器ip
host="172.17.0.3"
mysqlPort=3306
dbUser="shengli"
dbPwd="shengli0"

#数据库
configDB="fut_one_config"
hisTradingDataDB="fut_one_history_trading_data"
logDB="fut_one_log_data"
riskDB="fut_one_risk_data"
tradingDataDB="fut_one_trading_data"

todayWeek = datetime.datetime.now().weekday() + 1
today = datetime.datetime.now().strftime('%Y%m%d')
execLog = CLog(logName="remInstallMutliInstance_" + today + ".log", isPrint=True)
myDB = CMySqlDB(log=execLog, dbHost=host, dbPort=mysqlPort, dbName=configDB, dbUser=dbUser, dbPwd=dbPwd)


def popenLog(str = ""):
    os.system(str)
    execLog.log(str)

# 解析配置                                                      i
def getInstallInstancdNum():
    instanceNum = ["0"]

    numstr=""
    if ("-" in installInstanceUser):
        instanceNumBegAndEnd = installInstanceUser.split("-", 1)
        beg = int(instanceNumBegAndEnd[0])
        end = int(instanceNumBegAndEnd[1])
        while (beg != end + 1):
            instanceNum.append(str(beg))
            numstr = numstr + str(beg) + ","  
            beg = beg + 1
    else:
        instanceNum = installInstanceUser.split(",", -1)

    execLog.log("now time to install instance num :" + numstr)

    return instanceNum

# 安装前检查
def checkDirAndDBBeforeInstall(instanceNum=["0"]):
    myDB.query("show databases;")
    allDB = myDB.getData()

    existUser = ["user0"]
    existRemDirUser = ["user0"]
    allUser = popenLog("cat /etc/passwd")
    for line in allUser:
        userName = line[0:4]
        if ("user" == userName):
            userName = line.split(":", 1)[0]
            existUser.append(userName)
            if popenLog("ls /home/" + userName) is None:
                existRemDirUser.append(userName)

    for i in range(0, len(instanceNum)):
        # 跳过用户0
        if("0" == instanceNum[i]):
            continue

        dbName = instanceNum[i] + "_" + configDB
        userName = "user" + instanceNum[i]
        if dbName in allDB:
            # 检查数据库已存在 返回
            execLog.log("rem database for " + userName + " is alread exist, install end")
            return -1
        if userName in existRemDirUser:
            #检查主目录已存在 返回
            execLog.log("rem dir for " + userName + " is alread exist, install end")
            return -1


        if(userName not in existUser):
            popenLog("useradd " + userName)
            popenLog('echo "ShengliSoft@"'+instanceNum[i]+'|passwd  user$i --stdin')


    return 0


def replaceDirXml(userID = "12345"):
    xml = open("ees_db_entry.xml", mode = "r")
    xmlFileNew = open("/home/user" + userID + "/rem_one/lgs/ees_db_entry.xml", mode="w")
    lines = xml.readlines()
    for line in lines:
        lineStr=str(line)
        index = lineStr.find("fut_one")
        if(index < 0):
            xmlFileNew.write(lineStr)
        else:
            newLineStr = lineStr[0:index] + userID + "_" + lineStr[index:]
            xmlFileNew.write(newLineStr)


    xml.close()
    xmlFileNew.close()

    popenLog("cp /home/user" + userID + "/rem_one/lgs/ees_db_entry.xml /home/user" + userID + "/rem_one/hds/")
    popenLog("cp /home/user" + userID + "/rem_one/lgs/ees_db_entry.xml /home/user" + userID + "/rem_one/eqs0/")
    popenLog("cp /home/user" + userID + "/rem_one/lgs/ees_db_entry.xml /home/user" + userID + "/rem_one/ot0/")
    popenLog("cp /home/user" + userID + "/rem_one/lgs/ees_db_entry.xml /home/user" + userID + "/rem_one/bk/")
    popenLog("cp /home/user" + userID + "/rem_one/lgs/ees_db_entry.xml /home/user" + userID + "/rem_one/rs/")


def createDB(dbName="12345", userID ="12345"):
    dbNameNew = userID + "_" + dbName
    createDBSql = "DROP DATABASE IF EXISTS " + dbNameNew
    myDB.exec(createDBSql)
    createDBSql = "CREATE DATABASE IF NOT EXISTS " + dbNameNew
    myDB.exec(createDBSql)

def replaceIntoSymbolData(dbNameNew="12345", fileName=""):
    useDB = "use " + dbNameNew + ";"
    popenLog("rm -rf tmp.sql")
    sqlFile = open("tmp.sql", mode="w")
    sqlFile.write(useDB)
    sqlFile.close()
    # 建表，插数据
    execLog.log(useDB)
    popenLog("cat " + fileName + " >> tmp.sql")
    time.sleep(1)
    popenLog("mysql -u" + dbUser + " -p" + dbPwd + " < tmp.sql")

def sourceDB(dbName="configDB", userID="12345"):
    dbNameNew = userID + "_" + dbName
    useDB = "use " + dbNameNew + ";"
    popenLog("rm -rf tmp.sql")
    sqlFile = open("tmp.sql", mode="w")
    sqlFile.write(useDB)
    sqlFile.close()
    # 建表，插数据
    execLog.log(useDB)
    popenLog("cat " + dbName + ".sql" + " >> tmp.sql")
    time.sleep(1)
    popenLog("mysql -u" + dbUser + " -p" + dbPwd + " < tmp.sql")

def changeDBDate(userID="12345"):
    configDBNew = userID + "_" + configDB
    configDBInstanceNew = CMySqlDB(log=execLog, dbHost=host, dbPort=mysqlPort, dbName=configDBNew, dbUser=dbUser, dbPwd=dbPwd)
    # 端口配置
    sqlStr = "update t_global_settings set setting_value = " + str(int(userID) * 1000 + 2) + \
             " where setting_key = 'BK_SVR_PORT';"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "update t_global_settings set setting_value = " + str(int(userID) * 1000 + 3) + \
             " where setting_key = 'HDS_SVR_EMC_LISTEN_PORT';"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "update t_global_settings set setting_value = " + str(int(userID) * 1000 + 4) + \
             " where setting_key = 'HDS_SVR_HDC_LISTEN_PORT';"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "update t_global_settings set setting_value = " + str(int(userID) * 1000 + 5) + \
             " where setting_key = 'LOG_SERVER_PORT';"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "update t_ot_define set xml_cnf = replace(xml_cnf, '20000', '" + str(int(userID) * 1000) + "')"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "update t_ot_define set xml_cnf = replace(xml_cnf, '20001', '" + str(int(userID) * 1000 + 1) + "')"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "UPDATE t_eqs_define SET tcp_port = " + str(int(userID) * 1000 + 6) + \
             " WHERE eqs_id = 'eqs0';"
    configDBInstanceNew.exec(sqlStr)

    user = "user" + userID
    confDBName = userID + "_fut_one"
    # 数据库配置 计划任务
    sqlStr="UPDATE t_global_settings SET setting_value = replace(setting_value, 'user0'," + "'" + user + "'" + \
           ") WHERE setting_value LIKE '%user0%';"
    configDBInstanceNew.exec(sqlStr)
    sqlStr = "UPDATE t_global_settings SET setting_value = replace(setting_value, 'fut_one'," + "'" + confDBName + "'" + \
           ") WHERE setting_value LIKE '%fut_one%';"
    configDBInstanceNew.exec(sqlStr)



    # 账户用户
    for i in range(1, 61):
        noStr=str(i)
        if i < 10 :
            noStr = "00" + noStr
        else:
            noStr = "0" + noStr
        account = userID + "66" + noStr
        # 账户数据t_account_info
        sqlStr = "REPLACE INTO t_account_info (account_id, account_desc, ot_cluster_id, trade_previlege, last_update_time)  \
            VALUES('" + account + "','" + account + "','ot_cluster1', 0, '0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)

        # 交易编码
        sqlStr = "REPLACE INTO t_account_exchange_code(account_id, exchange_id, hedge_flag, exchange_code, last_update_time) \
            VALUES('" + account + "', 102, 2,'" + account + "102" + "','0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)
        sqlStr = "REPLACE INTO t_account_exchange_code(account_id, exchange_id, hedge_flag, exchange_code, last_update_time) \
            VALUES('" + account + "', 103, 2,'" + account + "103" + "','0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)
        sqlStr = "REPLACE INTO t_account_exchange_code(account_id, exchange_id, hedge_flag, exchange_code, last_update_time) \
            VALUES('" + account + "', 104, 2,'" + account + "104" + "','0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)
        sqlStr = "REPLACE INTO t_account_exchange_code(account_id, exchange_id, hedge_flag, exchange_code, last_update_time) \
            VALUES('" + account + "', 106, 2,'" + account + "106" + "','0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)

        # 初始权益
        sqlStr = "REPLACE INTO t_account_balance(account_id, day_init_balance, day_init_equity, last_update_time) \
            VALUES('" + account + "', '100000000.00', '100000000.00', '0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)

        # 用戶信息 * 2
        sqlStr = "REPLACE INTO t_user_info(user_id, login_id, md5_pwd, user_name, enabled, allow_mbl_query, \
                      allow_using_protocol, flowctrl_fusing, fusing_seconds, flowctrl_threshold, \
                      flowctrl_time, last_login_time, subscribe_type, create_time, active_time, last_update) \
        VALUES(" + str(i * 2) + ",'" + (account + "1") + "', 'C4CA4238A0B923820DCC509A6F75849B', '', 'Y', 'N', 'Y', 'Y', 30, 300, 1, \
               '0000-00-00 00:00:00', 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)
        sqlStr = "REPLACE INTO t_user_info(user_id, login_id, md5_pwd, user_name, enabled, allow_mbl_query, \
                              allow_using_protocol, flowctrl_fusing, fusing_seconds, flowctrl_threshold, \
                              flowctrl_time, last_login_time, subscribe_type, create_time, active_time, last_update) \
                VALUES(" + str(i * 2 + 1) + ",'" + (account + "2") + "', 'C4CA4238A0B923820DCC509A6F75849B', '', 'Y', 'N', 'Y', 'Y', 30, 300, 1, \
                       '0000-00-00 00:00:00', 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00');"
        configDBInstanceNew.exec(sqlStr)

        # 账户用户链接
        sqlStr = "REPLACE INTO t_account_user_link (account_id, user_id) VALUES ('" + account +"'," + str(i * 2)+ ");"
        configDBInstanceNew.exec(sqlStr)
        sqlStr = "REPLACE INTO t_account_user_link (account_id, user_id) VALUES ('" + account +"'," + str(i * 2 + 1)+ ");"
        configDBInstanceNew.exec(sqlStr)

def rePlaceShAndSqlToUserDir(userID="12345", fileName=""):
    if "0" == userID or ""== fileName:
        return

    popenLog("rm -rf tmp ")
    newFile=open("tmp", mode="w")
    oldFile=open(fileName, errors="ignore", mode="r")
    lines = oldFile.readlines()
    for line in lines:
        lineStr = str(line)
        index = lineStr.find("user0")
        if(index >= 0):
            newLine = lineStr[0:index+4] + userID + lineStr[index+5:]
            newFile.write(newLine)
            continue
        else:
            pass

        index = lineStr.find("fut_one")
        if (index >= 0):
            newLine = lineStr[0:index] + userID + "_" + lineStr[index:]
            newFile.write(newLine)
            continue
        else:
            newFile.write(lineStr)


    newFile.close()
    popenLog("cp tmp "+ "/home/user" + userID + "/rem_one/" + fileName + " -rf")



def install(instanceNum=["0"]):
    for userID in instanceNum:
        if "0" == userID:
            continue
        popenLog("rm  -rf /home/user" + userID + "/rem_one")
        popenLog("mkdir -p /home/user" + userID + "/rem_one")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/lgs")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/hds")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/eqs0")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/ot0")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/bk")
        popenLog("mkdir -p /home/user" + userID + "/rem_one/rs")
        popenLog("cp /home/user0/rem_one/lgs/ees_logger_server " + "/home/user" + userID + "/rem_one/lgs/")
        popenLog("cp /home/user0/rem_one/hds/ees_hds " + "/home/user" + userID + "/rem_one/hds/")
        popenLog("cp /home/user0/rem_one/eqs0/ees_eqs " + "/home/user" + userID + "/rem_one/eqs0/")
        popenLog("cp /home/user0/rem_one/ot0/ees_ot " + "/home/user" + userID + "/rem_one/ot0/")
        popenLog("cp /home/user0/rem_one/bk/ees_bk " + "/home/user" + userID + "/rem_one/bk/")
        popenLog("cp /home/user0/rem_one/rs/ees_rs " + "/home/user" + userID + "/rem_one/rs/")
        popenLog("cp -rf ~/.tmux.conf  " + "/home/user" + userID + "/")

        # 脚本处理
        rePlaceShAndSqlToUserDir(userID=userID, fileName="clear_ees_data.sql")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="makeneat.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="update_sm_and_bod.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="probe_start_primary.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="start_eqs_ot.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="start_primary.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="start_rem_all.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="start_secondary.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="stop_secondary.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="stop_primary.sh")
        rePlaceShAndSqlToUserDir(userID=userID, fileName="stop_rem.sh")

        execLog.log("install user dir finish " + userID)

        replaceDirXml(userID=userID)
        execLog.log("replace xml finish " + userID)

        createDB(dbName=configDB, userID=userID)
        createDB(dbName=logDB, userID=userID)
        createDB(dbName=riskDB, userID=userID)
        createDB(dbName=tradingDataDB, userID=userID)
        createDB(dbName=hisTradingDataDB, userID=userID)
        execLog.log("create database finish " + userID)

        sourceDB(dbName=configDB, userID=userID)

        sourceDB(dbName=logDB, userID=userID)
        sourceDB(dbName=riskDB, userID=userID)
        sourceDB(dbName=tradingDataDB, userID=userID)
        sourceDB(dbName=hisTradingDataDB, userID=userID)

        changeDBDate(userID=userID)
        execLog.log("change db conf data finish " + userID)

        # 合约参数
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_config", fileName="t_symbol_category.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_config", fileName="t_china_future_instrument.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_config", fileName="t_future_option_instrument.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_trading_data", fileName="t_close_report.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_trading_data", fileName="t_close_report_index.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_trading_data", fileName="t_close_report_opt.sql")
        replaceIntoSymbolData(dbNameNew=userID + "_fut_one_trading_data", fileName="t_new_dce_combo_priority.sql")
        execLog.log("replace into symbol data finish " + userID)

        #配置计划任务
        cron="05 00 * * * /home/user0/rem_one/start_secondary.sh > /home/user0/cron/cron_rem_one_secondary.log\n\
55 23 * * * /home/user0/rem_one/stop_secondary.sh > /home/user0/cron/cron_rem_one_secondary.log\n"
        for i  in range(0,4):
            index = cron.find("user0")
            if(index >= 0):
                cron=cron[0:index] + "user" + userID + cron[index + 4:]
                tmp=open("tmp", mode="w")
                tmp.write(cron)
                tmp.close()
                popenLog("cat tmp > /var/spool/cron/user" + userID)

        popenLog("chmod 777 -R " + "/home")

installInstances = getInstallInstancdNum()
# 追加式安装
if(0 == installOrigaType and 0 == ifInstanceUserExit):
    if(0 == checkDirAndDBBeforeInstall(instanceNum=installInstances)):
        install(instanceNum=installInstances)

#覆盖式安装
if (0 == installOrigaType and 1 == ifInstanceUserExit):
    install(instanceNum=installInstances)

# 从文件恢复
if(1 == installOrigaType):
    pass